#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/12/12 14:31
# @Author  : 赵在化
# @email  : zaihuazhao@163.com
# @File    : urls.py
import os

import time
from django.conf.urls import url
from django.views.decorators.csrf import csrf_exempt

from apps.open.handlers import stats, order, product, proxy, version, event, exam


def OpenedApiCaller(request, *args, **kwargs):
    execStartTime = time.time()
    realCall = kwargs.pop('_viewFunc')
    ret = realCall(request, *args, **kwargs)
    execEndTime = time.time()
    # 所有大于100ms的操作，产生日志告警
    opTime = execEndTime - execStartTime
    if (opTime > 0.1):
        stats.app_logger.warning('!! op takes %s seconds : function:%s %s  ' % (opTime, request.method, request.path))

    return ret


urlpatterns_api = []


def addPreCheck(urlpatterns, checkFunC):
    checkFunC = csrf_exempt(checkFunC)
    for pattern in urlpatterns:
        urlRegx = pattern[0]
        if type(urlRegx) != list:
            urlRegList = [urlRegx]
        else:
            urlRegList = urlRegx

        viewFunc = pattern[1]
        if len(pattern) == 2:
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, {'_viewFunc': viewFunc}))

        elif len(pattern) == 3:
            otherPara = pattern[2]
            otherPara['_viewFunc'] = viewFunc
            for one in urlRegList:
                urlpatterns_api.append(url(one, checkFunC, otherPara))
        else:
            # print '!!unsupported url format : %s' % pattern
            os._exit(3)

urlpatterns = [
    (r'^report/$', stats.handler.dispatch),
    (r'^order/$', order.handler.dispatch),
    (r'^yj_products/$', product.handler.dispatch),
    (r'^yj_proxy/$', proxy.handler.dispatch),
    (r'^version/$', version.handler.dispatch),
    ([r'^yj_event/$'], event.handler.dispatch),
    ([r'^yj_exam/$',
      r'^yj_exam/(?P<resource_id>\w+)/$'], exam.handler.dispatch),


]
addPreCheck(urlpatterns, OpenedApiCaller)
urlpatterns = urlpatterns_api